<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div>
        <el-input
          placeholder="用户名"
          size="normal"
          clearable
          style="width:250px"
          v-model="searchName"
        ></el-input>
        <el-button
          style="margin:0px 10px 0px 20px"
          type="primary"
          size="default"
          icon="el-icon-search"
          @click="searchUser"
          >查询</el-button
        >
        <el-button size="default" @click="searchName = ''">清空</el-button>
      </div>
      <div style="margin:40px 0px 20px 0px">
        <el-button
          style="marginRight:10px"
          type="primary"
          size="default"
          @click="onAddDialog"
          >添加</el-button
        >
        <el-button type="danger" size="default" @click="">批量删除</el-button>
      </div>
      <el-table style="width: 100%" border :data="userList">
        <el-table-column type="selection"> </el-table-column>
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column
          label="用户名"
          width="150"
          prop="username"
        ></el-table-column>
        <el-table-column
          label="用户昵称"
          width="150"
          prop="nickName"
        ></el-table-column>
        <el-table-column
          label="角色列表"
          width="300"
          prop="roleName"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          width="300"
          prop="gmtCreate"
        ></el-table-column>
        <el-table-column
          label="更新时间"
          width="300"
          prop="gmtModified"
        ></el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="{ row }">
            <div>
              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top-start"
              >
                <el-button
                  class="el-icon-user-solid"
                  type="info"
                  size="small"
                  @click="allot(row)"
                ></el-button>
              </el-tooltip>

              <el-tooltip
                class="item"
                effect="dark"
                content="修改用户"
                placement="top-start"
              >
                <el-button
                  type="primary"
                  size="small"
                  @click="updataUser(row)"
                  class="el-icon-edit-outline"
                ></el-button>
              </el-tooltip>

              <el-tooltip
                class="item"
                effect="dark"
                content="删除用户"
                placement="top-start"
              >
                <el-button
                  type="danger"
                  size="small"
                  @click="deleteUser(row.id)"
                  class="el-icon-delete"
                ></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size.sync="pageSize"
        layout="sizes, prev, pager, next,total"
        :total="total"
      >
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        :title="`${userId === 0 ? '添加' : '修改'}用户`"
        :visible.sync="dialogVisible_addUser"
        width="50%"
      >
        <el-form label-width="80px" :inline="false">
          <el-form-item label="用户名">
            <el-input v-model="userName"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input v-model="nickName"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" v-if="userId === 0">
            <el-input v-model="password"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible_addUser = false">取 消</el-button>
          <el-button type="primary" @click="saveAddUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 角色分配对话框 -->
      <el-dialog title="设置角色" :visible.sync="dialogVisible_acl" width="50%">
        <el-form label-width="80px" :inline="false">
          <el-form-item label="用户名">
            <el-input v-model="userName"></el-input>
          </el-form-item>
          <el-form-item label="角色列表">
            <el-checkbox
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
              v-model="checkAll"
              >全选</el-checkbox
            >
            <div style="margin: 10px 0;"></div>
            <el-checkbox-group
              v-model="assignRoles"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="role in allRolesList"
                :label="role"
                :key="role"
                >{{ role }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible_acl = false">取 消</el-button>
          <el-button type="primary" @click="saveAssign">保存</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  reqGetUserList,
  reqAddUser,
  reqSearchUser,
  reqRoleListByUserId,
  reqAssignRolesByUserId,
  reqUpdataUser,
  reqDeleteUser
} from "@/api/acl/user";
export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userList: [],
      dialogVisible_addUser: false, //展示添加用户框
      searchName: "", //搜索框数据
      userName: "", //用户名
      nickName: "", //用户昵称
      password: "", //用户密码
      dialogVisible_acl: false, //展示角色分配框
      allRolesList: [], //所有角色的名称
      assignRoles: [], //选中角色的名称
      isIndeterminate: true, //半选
      checkAll: false, //权限
      allRolesList_info: [], //所有角色信息
      userId: 0 //用户id
    };
  },
  methods: {
    // 获取分页用户列表
    async getUserList() {
      const result = await reqGetUserList(this.currentPage, this.pageSize);
      this.userList = result.data.items;
      this.total = result.data.total;
    },
    // 点击添加按钮
    onAddDialog() {
      this.dialogVisible_addUser = true;
      // 清空数据
      this.userId = 0;
      this.userName = "";
      this.nickName = "";
      this.password = "";
    },
    // 添加用户
    async saveAddUser() {
      // 收集数据
      const userInfo = {
        id: this.userId,
        username: this.userName,
        nickName: this.nickName,
        password: this.password
      };
      if (this.userId === 0) {
        // 发送添加请求
        await reqAddUser(userInfo);
      } else {
        // 发送修改请求
        await reqUpdataUser(userInfo);
      }

      // 关闭添加用户框
      this.dialogVisible_addUser = false;
      // 重新获取数据
      this.getUserList();
    },
    // 点击搜索
    async searchUser() {
      const result = await reqSearchUser(
        this.currentPage,
        this.pageSize,
        this.searchName
      );
      // console.log(result);
      this.userList = result.data.items;
      this.total = result.data.total;
    },
    // 点击分配角色
    async allot(row) {
      this.dialogVisible_acl = true;
      console.log(row);
      this.userId = row.id;
      // console.log(row);
      this.userName = row.username;
      const result = await reqRoleListByUserId(row.id);
      // console.log(result);
      this.allRolesList_info = result.data.allRolesList;
      this.allRolesList = result.data.allRolesList.map(item => item.roleName);
      this.assignRoles = result.data.assignRoles.map(item => item.roleName);
    },
    // 点击改变全选时间
    handleCheckAllChange(val) {
      this.assignRoles = val ? this.allRolesList : [];
      this.isIndeterminate = false;
    },
    // 点击角色框
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.allRolesList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.allRolesList.length;
    },
    // 点击保存分配角色
    async saveAssign() {
      // 收集数据

      const pitchRoles = this.allRolesList_info.reduce((p, c) => {
        const isInclude = this.assignRoles.includes(c.roleName);
        // console.log(p);
        if (isInclude) {
          // console.log(p);
          p.push(c.id);
          return p;
        } else {
          // console.log(p);
          return p;
        }
      }, []);
      // console.log(pitchRoles);
      // 发送请求
      console.log(this.userId, pitchRoles);
      await reqAssignRolesByUserId({ userId: this.userId, roleId: pitchRoles });

      // 关闭对话框
      this.dialogVisible_acl = false;
      // 重新获取数据
      this.getUserList();
    },

    // 修改用户信息
    updataUser(row) {
      // console.log(row);

      // 数据回填
      this.dialogVisible_addUser = true;
      this.userId = row.id;
      this.userName = row.username;
      this.nickName = row.nickName;
    },
    // 删除用户
    async deleteUser(id) {
      // 请求删除用户
      await reqDeleteUser(id);
      this.$message.success("删除成功！");
      // 请求新的数据
      this.getUserList();
    }
  },
  mounted() {
    this.getUserList();
  },
  watch: {
    currentPage() {
      this.getUserList();
    },
    pageSize() {
      this.getUserList();
    }
  }
};
</script>

<style lang="scss" scoped></style>
